import os.path
from datetime import datetime

from flask import Blueprint
from flask_restful import Resource, reqparse, inputs
from flask_restful import marshal_with, fields, marshal
from werkzeug.datastructures import FileStorage

from cfg import Config
from .model import User, Friend
from ..exts import api

user_db = Blueprint('user', __name__, url_prefix='/user_api')

#  之 出数据
'''
attribute=匹配model.py字段  # Renaming Attributes
absolute=True为绝对地址
'''
class CustomDateTime(fields.Raw):
    def format(self, value):
        if not isinstance(value, datetime):
            raise ValueError("Value must be a datetime object")
        return value.strftime('%Y-%m-%d %H:%M:%S')


class IsDelete(fields.Raw):
    def format(self, value):  # value是db的值
        print(value)
        return '已删除' if value else '存在'


user_fields1 = {
    'id': fields.Integer,
    'name': fields.String(attribute='username'),

    'password': fields.String,
    'reg_time': CustomDateTime(),
    'register_time': CustomDateTime(attribute='reg_time'),
    'icon': fields.String(attribute='avatar'),
    'isDelete': fields.Boolean(attribute='isDel'),
    'isDelete2': IsDelete(attribute='isDel'),

    'uri': fields.Url('single_user'),
    'https_uri': fields.Url('single_user', absolute=True, scheme='https'),
}

# POST model.py字段 之进数据
parser = reqparse.RequestParser(bundle_errors=True)  # 参数解析
parser.add_argument('username', type=str, required=True, help='must用户名', location=['form', 'json'])
parser.add_argument('password', type=inputs.regex(r'^\d{6, 12}$'), required=True, help='must密码', location=['form', 'json'])
parser.add_argument('phone', type=inputs.regex(r'^1[3-9]\d{9}$'), location=['form', 'json'])
parser.add_argument('hobby', action='append')  # 多选框
parser.add_argument('avatar', type=FileStorage, location='files')


class UsersResource(Resource):
    @marshal_with(user_fields1)
    def get(self):
        users = User.query.all()
        return users

    @staticmethod
    def post():
        pass

    def put(self):
        return {'msg': 'successful', 'method': 'put'}

    def delete(self):
        return {'msg': 'successful', 'method': 'delete'}

    def patch(self):
        return {'msg': 'successful', 'method': 'patch'}


class UserSingleResource(Resource):
    @marshal_with(user_fields1)
    def get(self, id):
        user = User.query.get(id)
        return user

    @marshal_with(user_fields1)
    def post(self, id):
        args = parser.parse_args()  # 参数验证
        username = args.get('username')
        password = args.get('password')
        avatar = args.get('avatar')

        user = User()
        phone = args.get('phone')
        user.username = username
        user.password = password
        if avatar:
            up = os.path.join(Config.UPLOAD_ICON_DIR, avatar.filename)
            avatar.save(up)
            user.avatar = os.path.join('upload/icon', avatar.filename)
        if phone:
            user.phone = phone
        user.save_user()

        return user

    def delete(self, id):
        pass

user_friend_fields = {
    'username': fields.String,
    'num': fields.Integer,
    'friends': fields.List(fields.Nested(user_fields1))
}

class UserFriendResource(Resource):
    def get(self, id):
        friends = Friend.query.filter(Friend.uid == id).all()
        user = User.query.get(id)

        friend_list = []
        for friend in friends:
            u = User.query.get(friend.fid)
            friend_list.append(u)

        data = {
            'username': user.username,
            'num': len(friends),
            'friends': marshal(friend_list, user_fields1)
        }
        return data



api.add_resource(UsersResource, '/users', endpoint='all_user')
api.add_resource(UserSingleResource, '/user/<int:id>', endpoint='single_user')
api.add_resource(UserFriendResource, '/friend/<int:id>', endpoint='user_friend')